 package com.heo.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.heo.dao.DeviceInfoMapper;
import com.heo.pojo.CommandResult;
import com.heo.pojo.ControlInfoEntity;
import com.heo.pojo.DeviceInfoEntity;
import com.heo.pojo.DeviceLockInfoEntity;
import com.heo.pojo.DeviceModelEntity;
import com.heo.pojo.OrgInfoEntity;
import com.heo.pojo.req.QueryDevicePara;
import com.heo.pojo.req.QueryDeviceStatusPara;
import com.heo.pojo.req.QueryDeviceTypePara;
import com.heo.pub.DictEnum;
import com.heo.service.DeviceChannelService;
import com.heo.service.DeviceInfoService;
import com.heo.service.DeviceModelService;
import com.heo.service.OrgInfoService;
import com.heo.util.RedisUtil;

/**
 * @author chichi
 */

@Controller
@Scope("singleton") // 1、为了性能。2、不需要多例。只要controller中不定义属性，那么单例完全是安全的。
@RequestMapping("/")
public class QueryController extends BaseController
{
  private static Logger log = Logger.getLogger(QueryController.class);

  @Resource(name = "orgInfoService")
  private OrgInfoService orgInfoService;

  @Resource(name = "deviceInfoService")
  private DeviceInfoService deviceInfoService;

  @Resource(name = "deviceChannelService")
  private DeviceChannelService deviceChannelService;
  
  @Resource(name = "deviceModelService")
  private DeviceModelService deviceModelService;
  
  @Autowired
  private DeviceInfoMapper deviceInfoMapper;

  /**
   * 统计设备信息
   * 
   * @param session
   * @param request
   * @param QueryStatPara
   * @return
   */
  @ResponseBody
  @RequestMapping(value = "/query_device_status.do", method =
  { RequestMethod.POST })
  public JSONObject queryDevice(HttpSession session, HttpServletRequest request, @RequestBody QueryDeviceStatusPara queryDeviceStatusPara)
  {
    try
    {
      log.debug("[查询设备状态]收到请求参数：" + queryDeviceStatusPara.toString());

      // 校验参数
      HashMap<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("appId", queryDeviceStatusPara.getAppId());
      paraMap.put("appSecret", queryDeviceStatusPara.getAppSecret());
      List<OrgInfoEntity> orgList = orgInfoService.listByMap(paraMap, "listByAppId");
      if (orgList == null || orgList.size() != 1)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      if (orgList == null || orgList.size() != 1)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      // 判断appid是否合法
      if (!(orgList.get(0).getAppId().equals(queryDeviceStatusPara.getAppId()) && orgList.get(0).getAppSecret().equals(queryDeviceStatusPara.getAppSecret())))
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }

      // 请求方没有传设备参数过来，先去数据库找全部的设备
      paraMap = new HashMap<String, Object>();
      paraMap.put("appId", queryDeviceStatusPara.getAppId());
      paraMap.put("appSecret", queryDeviceStatusPara.getAppSecret());
      List<DeviceInfoEntity> deviceList = deviceInfoService.listByMap(paraMap, "selectAllByAppId");
      if (deviceList == null)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.SUCCESS, CommandResult.PublicResultMsg.SUCCESS);
        return JSON.parseObject(commandResult.toString());
      }

      StringBuffer onlineSb = new StringBuffer();
      StringBuffer offlineSb = new StringBuffer();

      // 查询当前appid下的设备，然后开始做统计
      Set<String> deviceStatusSet = RedisUtil.keys("\\[DEVICE_CONTROL\\]" + queryDeviceStatusPara.getAppId() + "*");

      log.debug("查询到keys的内容为：" + deviceStatusSet);

      for (int i = 0; i < deviceList.size(); i++)
      {
        String imei = deviceList.get(i).getDeviceImei();
        if (deviceStatusSet.contains(DictEnum.RedisKey.DEVICE_CONTROL + queryDeviceStatusPara.getAppId() + ":" + imei))
        {
          // 这里是在线的
          onlineSb.append(imei);
          onlineSb.append(",");
        }
        else
        {
          // 这里是离线的
          offlineSb.append(imei);
          offlineSb.append(",");
        }
      }

      String onlineStr = onlineSb.toString();
      onlineStr = onlineStr.length() == 0 ? "" : onlineStr.substring(0, onlineStr.length() - 1);

      String offlineStr = offlineSb.toString();
      offlineStr = offlineStr.length() == 0 ? "" : offlineStr.substring(0, offlineStr.length() - 1);

      CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.SUCCESS, CommandResult.PublicResultMsg.SUCCESS);

      if ("ONLINE".equalsIgnoreCase(queryDeviceStatusPara.getDeviceStatus()))
      {
        // 查在线的
        commandResult.setDeviceResultList(onlineStr);
      }
      else if ("OFFLINE".equalsIgnoreCase(queryDeviceStatusPara.getDeviceStatus()))
      {
        // 查离线
        commandResult.setDeviceResultList(offlineStr);
      }

      return JSON.parseObject(commandResult.toString());
    }
    catch (Exception e)
    {
      log.error(e.getMessage(), e);
      // 未知错误
      CommandResult pushResult = new CommandResult(CommandResult.PublicResultCode.UNKNOW_ERROR, CommandResult.PublicResultMsg.UNKNOW_ERROR);
      return JSON.parseObject(pushResult.toString());
    }
  }

  /**
   * 查询设备状态
   * 
   * @param session
   * @param request
   * @param queryDevicePara
   * @return
   */
  @ResponseBody
  @RequestMapping(value = "/query.do", method =
  { RequestMethod.POST })
  public JSONObject queryDevice(HttpSession session, HttpServletRequest request, @RequestBody QueryDevicePara queryDevicePara)
  {
    try
    {
      log.debug("[查询设备状态]收到请求参数：" + queryDevicePara.toString());
      // 校验参数
      if (StringUtils.isEmpty(queryDevicePara.getDeviceIMEI()))
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.PARA_ERROR, CommandResult.PublicResultMsg.PARA_ERROR);
        commandResult.setChannelInfoList(null);
        return JSON.parseObject(commandResult.toString());
      }
      // 找设备的信息
      DeviceInfoEntity deviceInfo = deviceInfoService.getByKey(queryDevicePara.getDeviceIMEI());
      if (deviceInfo == null || deviceInfo.getOrgInfoEntity() == null)
      {
        // 设备不存在。device_info是子表，并且有做关联，所以不可能出现子表有数据，父表没数据的情况。所以如果找不到数据，一定是子表没数据。
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.DEVICE_IS_NOT_EXIST, CommandResult.PublicResultMsg.DEVICE_IS_NOT_EXIST);
        commandResult.setChannelInfoList(null);
        return JSON.parseObject(commandResult.toString());
      }
      // 判断appid是否合法
      if (!(deviceInfo.getOrgInfoEntity().getAppId().equals(queryDevicePara.getAppId()) && deviceInfo.getOrgInfoEntity().getAppSecret().equals(queryDevicePara.getAppSecret())))
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        commandResult.setChannelInfoList(null);
        return JSON.parseObject(commandResult.toString());
      }
      // 判断设备的通道参数是否合法
      if (!StringUtils.isEmpty(queryDevicePara.getDeviceChannelIndex()))
      {
        if (queryDevicePara.getDeviceChannelIndex() + 1 > deviceInfo.getDeviceChannelNum())
        {
          CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.DEVICE_CHANNEL_INDEX_NOT_EXIST, CommandResult.PublicResultMsg.DEVICE_CHANNEL_INDEX_NOT_EXIST);
          return JSON.parseObject(commandResult.toString());
        }
      }
      
      // 去redis里找设备的控制信息
      Object redisObj = RedisUtil.getValue(DictEnum.RedisKey.DEVICE_CONTROL + queryDevicePara.getAppId() + ":" + queryDevicePara.getDeviceIMEI());
      if (redisObj == null)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.DEVICE_IS_OFFLINE, CommandResult.PublicResultMsg.DEVICE_IS_OFFLINE);
        commandResult.setChannelInfoList(null);
        commandResult.setDeviceInfo(deviceInfo);// 把设备的对象返回回去，业务系统中可以查到参数
        return JSON.parseObject(commandResult.toString());
      }
      // 查询redis里设备的状态。然后返回
      ControlInfoEntity controlInfo = (ControlInfoEntity) JSON.parseObject(redisObj.toString(), ControlInfoEntity.class);

      CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.SUCCESS, CommandResult.PublicResultMsg.SUCCESS);
      commandResult.setSignal(controlInfo.getSignal());// 返回设备的信号强度
      commandResult.setDeviceInfo(deviceInfo);// 把设备的对象返回回去，业务系统中可以查到参数
      
      int i = 0;
      while (true)
      {
        // 如果有送参数进来，要查询某一个通道的状态，就直接查询后输出
        if (queryDevicePara.getDeviceChannelIndex() != null)
        {
          String[] statusArray = statusConvertText(controlInfo.getChannelStatus(queryDevicePara.getDeviceChannelIndex()));
          // 获取设备锁定状态
          String lockStatus = null;// 锁定状态
          Long lockEndTime = null;// 锁定剩余时间
          String lockTocken = null;
          String redisLockKey = DictEnum.RedisKey.LOCK_STATUS + queryDevicePara.getAppId() + ":" + queryDevicePara.getDeviceIMEI() + ":" + queryDevicePara.getDeviceChannelIndex();
          redisObj = RedisUtil.getValue(redisLockKey);
          if (redisObj == null)
          {
            lockStatus = DictEnum.DeviceChannelLockStatus.UNLOCKED;
            lockEndTime = null;
            lockTocken = null;
          }
          else
          {
            DeviceLockInfoEntity lockInfo = (DeviceLockInfoEntity) JSON.parseObject(redisObj.toString(), DeviceLockInfoEntity.class);
            lockStatus = DictEnum.DeviceChannelLockStatus.LOCKED;
            lockEndTime = lockInfo.getLockEndTime();
            lockTocken = lockInfo.getLockTocken();
          }

          // 从redis里获取回调参数
          Object callParaObj = RedisUtil.getValue(DictEnum.RedisKey.CALLBACK_INFO + queryDevicePara.getAppId() + ":" + queryDevicePara.getDeviceIMEI() + ":" + queryDevicePara.getDeviceChannelIndex());
          String errorCode = controlInfo.getChannelErrorCode(queryDevicePara.getDeviceChannelIndex());
          String errorText = controlInfo.getChannelErrorText(queryDevicePara.getDeviceChannelIndex());
          if (callParaObj != null)
          {
            commandResult.addChanelInfo(queryDevicePara.getDeviceChannelIndex(), statusArray[0], statusArray[1], callParaObj.toString(), lockStatus, lockEndTime, lockTocken,errorCode,errorText);
          }
          else
          {
            commandResult.addChanelInfo(queryDevicePara.getDeviceChannelIndex(), statusArray[0], statusArray[1], null, lockStatus, lockEndTime, lockTocken,errorCode,errorText);
          }
          return JSON.parseObject(commandResult.toString());
        }
        else
        {
          // 查询所有通道状态，从第0个通道开始遍历查询，一直查到没有
          Byte status = controlInfo.getChannelStatus(i);
          if (status == null)
          {
            // 后面没有了
            break;
          }
          else
          {
            String[] statusArray = statusConvertText(status);

            // 获取设备锁定状态
            String lockStatus = null;// 锁定状态
            Long lockEndTime = null;// 锁定剩余时间
            String lockTocken = null;
            String redisLockKey = DictEnum.RedisKey.LOCK_STATUS + queryDevicePara.getAppId() + ":" + queryDevicePara.getDeviceIMEI() + ":" + i;
            redisObj = RedisUtil.getValue(redisLockKey);
            if (redisObj == null)
            {
              lockStatus = DictEnum.DeviceChannelLockStatus.UNLOCKED;
              lockEndTime = null;
              lockTocken = null;
            }
            else
            {
              DeviceLockInfoEntity lockInfo = (DeviceLockInfoEntity) JSON.parseObject(redisObj.toString(), DeviceLockInfoEntity.class);
              lockStatus = DictEnum.DeviceChannelLockStatus.LOCKED;
              lockEndTime = lockInfo.getLockEndTime();
              lockTocken = lockInfo.getLockTocken();
            }

            // 从redis里获取回调参数
            Object callParaObj = RedisUtil.getValue(DictEnum.RedisKey.CALLBACK_INFO + queryDevicePara.getAppId() + ":" + queryDevicePara.getDeviceIMEI() + ":" + i);
            String errorCode = controlInfo.getChannelErrorCode(i);
            String errorText = controlInfo.getChannelErrorText(i);
            if (callParaObj != null)
            {
              commandResult.addChanelInfo(i, statusArray[0], statusArray[1], callParaObj.toString(), lockStatus, lockEndTime, lockTocken,errorCode,errorText);
            }
            else
            {
              commandResult.addChanelInfo(i, statusArray[0], statusArray[1], null, lockStatus, lockEndTime, lockTocken,errorCode,errorText);
            }
          }
        }
        i++;
      }
      return JSON.parseObject(commandResult.toString());
    }
    catch (Exception e)
    {
      log.error(e.getMessage(), e);
      // 未知错误
      CommandResult pushResult = new CommandResult(CommandResult.PublicResultCode.UNKNOW_ERROR, CommandResult.PublicResultMsg.UNKNOW_ERROR);
      pushResult.setChannelInfoList(null);
      return JSON.parseObject(pushResult.toString());
    }
  }
  

  /**
   * 查询设备状态
   * 
   * @param session
   * @param request
   * @param queryDevicePara
   * @return
   */
  @ResponseBody
  @RequestMapping(value = "/query_all_device.do", method =
  { RequestMethod.POST })
  public JSONObject queryAllDevice(HttpSession session, HttpServletRequest request, @RequestBody QueryDevicePara queryDevicePara)
  {
	JSONObject commandResultObject=new JSONObject();
    try
    {
      log.debug("[查询设备状态]收到请求参数：" + queryDevicePara.toString());
      // 校验参数
      if (StringUtils.isEmpty(queryDevicePara))
      {
        return commandResultObject;
      }
      List<String> listImei = JSONObject.parseArray(queryDevicePara.getDeviceIMEI(), String.class);
      // 找设备的信息
      List<DeviceInfoEntity> deviceInfoList = deviceInfoMapper.getByListImei("getByListImei", listImei);
			
        //QueryDevicePara queryDevicePara = queryDeviceParaList.get(0);
        for (int j = 0; j < deviceInfoList.size(); j++) {
        	DeviceInfoEntity deviceInfo = deviceInfoList.get(j);
            String deviceImei = deviceInfo.getDeviceImei();
    	   //DeviceInfoEntity deviceInfo = deviceInfoService.getByKey(queryDevicePara.getDe viceIMEI());
    	  if (deviceInfo == null || deviceInfo.getOrgInfoEntity() == null)
          {
            // 设备不存在。device_info是子表，并且有做关联，所以不可能出现子表有数据，父表没数据的情况。所以如果找不到数据，一定是子表没数据。
            CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.DEVICE_IS_NOT_EXIST, CommandResult.PublicResultMsg.DEVICE_IS_NOT_EXIST);
            commandResultObject.put(deviceImei, commandResult);
            continue;
          }
          // 判断appid是否合法
          if (!(deviceInfo.getOrgInfoEntity().getAppId().equals(queryDevicePara.getAppId()) && deviceInfo.getOrgInfoEntity().getAppSecret().equals(queryDevicePara.getAppSecret())))
          {
            CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
            commandResult.setChannelInfoList(null);
            commandResultObject.put(deviceImei, commandResult);
            continue;
          }
          // 判断设备的通道参数是否合法
          if (!StringUtils.isEmpty(queryDevicePara.getDeviceChannelIndex()))
          {
            if (queryDevicePara.getDeviceChannelIndex() + 1 > deviceInfo.getDeviceChannelNum())
            {
              CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.DEVICE_CHANNEL_INDEX_NOT_EXIST, CommandResult.PublicResultMsg.DEVICE_CHANNEL_INDEX_NOT_EXIST);
              commandResult.setChannelInfoList(null);
              commandResultObject.put(deviceImei, commandResult);
              continue;
            }
          }
          
          // 去redis里找设备的控制信息
          Object redisObj = RedisUtil.getValue(DictEnum.RedisKey.DEVICE_CONTROL + queryDevicePara.getAppId() + ":" + deviceImei);
          if (redisObj == null)
          {
            CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.DEVICE_IS_OFFLINE, CommandResult.PublicResultMsg.DEVICE_IS_OFFLINE);
            commandResult.setChannelInfoList(null);
            commandResult.setDeviceInfo(deviceInfo);// 把设备的对象返回回去，业务系统中可以查到参数
            commandResultObject.put(deviceImei, commandResult);
            continue;
          }
          // 查询redis里设备的状态。然后返回
          ControlInfoEntity controlInfo = (ControlInfoEntity) JSON.parseObject(redisObj.toString(), ControlInfoEntity.class);

          CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.SUCCESS, CommandResult.PublicResultMsg.SUCCESS);
          commandResult.setSignal(controlInfo.getSignal());// 返回设备的信号强度
          commandResult.setDeviceInfo(deviceInfo);// 把设备的对象返回回去，业务系统中可以查到参数
          int i = 0;
          while (true)
          {
            // 如果有送参数进来，要查询某一个通道的状态，就直接查询后输出
            if (queryDevicePara.getDeviceChannelIndex() != null)
            {
              String[] statusArray = statusConvertText(controlInfo.getChannelStatus(queryDevicePara.getDeviceChannelIndex()));
              // 获取设备锁定状态
              String lockStatus = null;// 锁定状态
              Long lockEndTime = null;// 锁定剩余时间
              String lockTocken = null;
              String redisLockKey = DictEnum.RedisKey.LOCK_STATUS + queryDevicePara.getAppId() + ":" + deviceImei + ":" + queryDevicePara.getDeviceChannelIndex();
              redisObj = RedisUtil.getValue(redisLockKey);
              if (redisObj == null)
              {
                lockStatus = DictEnum.DeviceChannelLockStatus.UNLOCKED;
                lockEndTime = null;
                lockTocken = null;
              }
              else
              {
                DeviceLockInfoEntity lockInfo = (DeviceLockInfoEntity) JSON.parseObject(redisObj.toString(), DeviceLockInfoEntity.class);
                lockStatus = DictEnum.DeviceChannelLockStatus.LOCKED;
                lockEndTime = lockInfo.getLockEndTime();
                lockTocken = lockInfo.getLockTocken();
              }

              // 从redis里获取回调参数
              Object callParaObj = RedisUtil.getValue(DictEnum.RedisKey.CALLBACK_INFO + queryDevicePara.getAppId() + ":" + deviceImei + ":" + queryDevicePara.getDeviceChannelIndex());
              String errorCode = controlInfo.getChannelErrorCode(queryDevicePara.getDeviceChannelIndex());
              String errorText = controlInfo.getChannelErrorText(queryDevicePara.getDeviceChannelIndex());
              if (callParaObj != null)
              {
                commandResult.addChanelInfo(queryDevicePara.getDeviceChannelIndex(), statusArray[0], statusArray[1], callParaObj.toString(), lockStatus, lockEndTime, lockTocken,errorCode,errorText);
              }
              else
              {
                commandResult.addChanelInfo(queryDevicePara.getDeviceChannelIndex(), statusArray[0], statusArray[1], null, lockStatus, lockEndTime, lockTocken,errorCode,errorText);
              }
              break;
            }
            else
            {
              // 查询所有通道状态，从第0个通道开始遍历查询，一直查到没有
              Byte status = controlInfo.getChannelStatus(i);
              if (status == null)
              {
                // 后面没有了
                break;
              }
              else
              {
                String[] statusArray = statusConvertText(status);

                // 获取设备锁定状态
                String lockStatus = null;// 锁定状态
                Long lockEndTime = null;// 锁定剩余时间
                String lockTocken = null;
                String redisLockKey = DictEnum.RedisKey.LOCK_STATUS + queryDevicePara.getAppId() + ":" + deviceImei + ":" + i;
                redisObj = RedisUtil.getValue(redisLockKey);
                if (redisObj == null)
                {
                  lockStatus = DictEnum.DeviceChannelLockStatus.UNLOCKED;
                  lockEndTime = null;
                  lockTocken = null;
                }
                else
                {
                  DeviceLockInfoEntity lockInfo = (DeviceLockInfoEntity) JSON.parseObject(redisObj.toString(), DeviceLockInfoEntity.class);
                  lockStatus = DictEnum.DeviceChannelLockStatus.LOCKED;
                  lockEndTime = lockInfo.getLockEndTime();
                  lockTocken = lockInfo.getLockTocken();
                }

                // 从redis里获取回调参数
                Object callParaObj = RedisUtil.getValue(DictEnum.RedisKey.CALLBACK_INFO + queryDevicePara.getAppId() + ":" + deviceImei + ":" + i);
                String errorCode = controlInfo.getChannelErrorCode(i);
                String errorText = controlInfo.getChannelErrorText(i);
                if (callParaObj != null)
                {
                  commandResult.addChanelInfo(i, statusArray[0], statusArray[1], callParaObj.toString(), lockStatus, lockEndTime, lockTocken,errorCode,errorText);
                }
                else
                {
                  commandResult.addChanelInfo(i, statusArray[0], statusArray[1], null, lockStatus, lockEndTime, lockTocken,errorCode,errorText);
                }
              }
            }
            i++;
          }
          commandResultObject.put(deviceImei, commandResult);
	}
      
      return commandResultObject;
    }
    catch (Exception e)
    {
      log.error(e.getMessage(), e);
      // 未知错误
      return commandResultObject;
    }
  }
  

  /**
   * 查询系统里所有可用的设备类型
   * @param session
   * @param request
   * @param queryDeviceStatusPara
   * @return
   */
  @ResponseBody
  @RequestMapping(value = "/query_all_device_type.do", method =
  { RequestMethod.POST })
  public JSONObject queryDeviceType(HttpSession session, HttpServletRequest request, @RequestBody QueryDeviceTypePara queryDeviceTypePara)
  {
    try
    {
      log.debug("[查询设备类型]收到请求参数：" + queryDeviceTypePara.toString());

      // 校验参数
      HashMap<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("appId", queryDeviceTypePara.getAppId());
      paraMap.put("appSecret", queryDeviceTypePara.getAppSecret());
      List<OrgInfoEntity> orgList = orgInfoService.listByMap(paraMap, "listByAppId");
      if (orgList == null || orgList.size() != 1)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      if (orgList == null || orgList.size() != 1)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      // 判断appid是否合法
      if (!(orgList.get(0).getAppId().equals(queryDeviceTypePara.getAppId()) && orgList.get(0).getAppSecret().equals(queryDeviceTypePara.getAppSecret())))
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }

      // 请求方没有传设备参数过来，先去数据库找全部的设备
      List<DeviceModelEntity> deviceModelList = deviceModelService.listAll();
      CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.SUCCESS, CommandResult.PublicResultMsg.SUCCESS);
      JSONObject result = JSON.parseObject(commandResult.toString());
      result.put("deviceModelList", deviceModelList);
      
      return result;
    }
    catch (Exception e)
    {
      log.error(e.getMessage(), e);
      // 未知错误
      CommandResult pushResult = new CommandResult(CommandResult.PublicResultCode.UNKNOW_ERROR, CommandResult.PublicResultMsg.UNKNOW_ERROR);
      return JSON.parseObject(pushResult.toString());
    }
  }
  
  /**
   * 根据设备的类型，来查符合该类型的设备iemi号列表
   * @param session
   * @param request
   * @param queryDeviceStatusPara
   * @return
   */
  @ResponseBody
  @RequestMapping(value = "/query_all_device_by_model_id.do", method =
  { RequestMethod.POST })
  public JSONObject queryDeviceByModelId(HttpSession session, HttpServletRequest request, @RequestBody QueryDeviceStatusPara queryDeviceStatusPara)
  {
    try
    {
      log.debug("[查询设备状态]收到请求参数：" + queryDeviceStatusPara.toString());

      // 校验参数
      HashMap<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("appId", queryDeviceStatusPara.getAppId());
      paraMap.put("appSecret", queryDeviceStatusPara.getAppSecret());
      List<OrgInfoEntity> orgList = orgInfoService.listByMap(paraMap, "listByAppId");
      if (orgList == null || orgList.size() != 1)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      if (orgList == null || orgList.size() != 1)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      // 判断appid是否合法
      if (!(orgList.get(0).getAppId().equals(queryDeviceStatusPara.getAppId()) && orgList.get(0).getAppSecret().equals(queryDeviceStatusPara.getAppSecret())))
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }

      // 请求方没有传设备参数过来，先去数据库找全部的设备
      paraMap = new HashMap<String, Object>();
      paraMap.put("appId", queryDeviceStatusPara.getAppId());
      paraMap.put("appSecret", queryDeviceStatusPara.getAppSecret());
      paraMap.put("deviceModelId", queryDeviceStatusPara.getDeviceModelId());
      List<DeviceInfoEntity> deviceList = deviceInfoService.listByMap(paraMap, "selectAllByDeviceModelId");
      if (deviceList == null)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.SUCCESS, CommandResult.PublicResultMsg.SUCCESS);
        return JSON.parseObject(commandResult.toString());
      }

      StringBuffer result = new StringBuffer();

      for (int i = 0; i < deviceList.size(); i++)
      {
        String imei = deviceList.get(i).getDeviceImei();
        result.append(imei);
        result.append(",");
      }

      String resultStr = result.toString();
      resultStr = resultStr.length() == 0 ? "" : resultStr.substring(0, resultStr.length() - 1);

      CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.SUCCESS, CommandResult.PublicResultMsg.SUCCESS);
      commandResult.setDeviceResultList(resultStr);

      return JSON.parseObject(commandResult.toString());
    }
    catch (Exception e)
    {
      log.error(e.getMessage(), e);
      // 未知错误
      CommandResult pushResult = new CommandResult(CommandResult.PublicResultCode.UNKNOW_ERROR, CommandResult.PublicResultMsg.UNKNOW_ERROR);
      return JSON.parseObject(pushResult.toString());
    }
  }
}
